<template>
  <!-- 登录的表单 -->
  <el-form
    ref="loginForms"
    class="relative max-sm:w-[70%] max-sm:top-[25vh] max-sm:mx-auto sm:w-[80%] sm:top-[30vh] bg-cover-500 p-10"
    :model="loginForm"
    :rules="rules"
    @keyup.enter="login"
  >
    <h1 class="text-white text-[40px]">{{ t('pageLogin.hello') }}</h1>
    <h2 class="text-white text-xl my-5">{{ t('pageLogin.welcomeBMC') }}</h2>
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" :prefix-icon="User" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        :prefix-icon="Lock"
        show-password
      />
    </el-form-item>
    <language-control>
      <template #default="{ switchLanguage }">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="t('pageLogin.switchLanguage')"
          placement="left-end"
        >
          <p
            class="float-right text-white hover:cursor-pointer hover:underline decoration-solid"
            @click="switchLanguage"
          >
            {{ t('pageLogin.currentLanguage') }}
          </p>
        </el-tooltip>
      </template>
    </language-control>
    <el-form-item>
      <el-checkbox v-model="rememberPassword" class="text-white">{{
        t('pageLogin.rememberPassword')
      }}</el-checkbox>
    </el-form-item>
    <el-form-item>
      <el-button
        :loading="loading"
        class="w-full bg-[var(--el-color-primary)]"
        type="primary"
        @click="login"
      >
        {{ t('pageLogin.logIn') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { Lock, User } from '@element-plus/icons-vue';
import { getTime } from '@/utilities/getTime';
import { useAuthenticationStore } from '@/store/Authentication/Authentication';
import { useGlobalStore } from '@/store/global';
import { useI18n } from 'vue-i18n';
import Cookies from 'js-cookie';
import useVuelidateTool from '@/hooks/useVuelidateTool';
import LanguageControl from '@/components/global/LanguageControl.vue';

const authenticationStore = useAuthenticationStore();
const globalStore = useGlobalStore();
const i18n = useI18n();
const { t, locale } = toRefs(i18n);
const loginForms = ref();
const $router = useRouter();
const loading = ref(false);
const loginForm = reactive({ username: '', password: '' });
const rememberPassword = ref(true);
const { useVuelidate, required, minLength, maxLength, elementInputValidator } =
  useVuelidateTool();

// Read remembered user information.
try {
  loginForm.username = JSON.parse(
    Cookies.get('rememberInfo') as string,
  ).username;
  loginForm.password = JSON.parse(
    Cookies.get('rememberInfo') as string,
  ).password;
} catch {
  // Do nothing.
  () => {};
}

// Set vuelidate rules.
const v$ = useVuelidate(
  {
    username: {
      required,
    },
    password: { required, minLength: minLength(6), maxLength: maxLength(16) },
  },
  loginForm,
);

// validators
const rules = computed(() => {
  return {
    username: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'username'),
      },
    ],
    password: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'password'),
      },
    ],
  };
});

// login request
const login = async () => {
  // loading
  loading.value = true;
  try {
    await authenticationStore.login(loginForm);
    localStorage.setItem('storedUsername', loginForm.username);
    globalStore.setUsername(loginForm.username);
    globalStore.setLanguagePreference(locale.value);
    const {
      PasswordChangeRequired,
      RoleId,
    }: { PasswordChangeRequired: boolean; RoleId: string } =
      await authenticationStore.getUserInfo(loginForm.username);
    if (PasswordChangeRequired) {
      $router.push('/change-password');
    } else {
      $router.push('/');
    }
    if (RoleId) {
      globalStore.userPrivilege = RoleId;
    }
    if (rememberPassword.value) {
      Cookies.set(
        'rememberInfo',
        `{"username": "${loginForm.username}","password": "${loginForm.password}"}`,
        { expires: 7 },
      );
    } else {
      Cookies.set('rememberInfo', `{"username": "${loginForm.username}"}`, {
        expires: 7,
      });
    }
    $router.push('/');
    ElNotification({
      type: 'success',
      message: i18n.t('pageLogin.alert.logSuccess'),
      title: i18n.t('pageLogin.alert.greeting', { getTime: getTime() }),
    });
    loading.value = false;
  } catch (error) {
    // login failed
    loading.value = false;
    ElNotification({
      type: 'error',
      message: i18n.t('pageLogin.alert.ErrorLogin'),
    });
  }
};
</script>
